/* eslint-disable camelcase */
import {
  ApiResponse,
  ArticleDetail,
  Comment,
  CommentDetail
} from '@/types/data'
import { RootThunkAction } from '@/types/store'
import request from '@/utils/request'

export function getArticleInfo (id: string): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<ArticleDetail>>(`/articles/${id}`)
    console.log('文章详情是', res.data.data)

    dispatch({
      type: 'articleDetail/setArticleInfo',
      payload: res.data.data
    })
  }
}

// 获取文章的评论
export function getCommentList (
  id: string,
  offset: string | null = null
): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<Comment>>('/comments', {
      params: {
        type: 'a',
        source: id,
        offset,
        limit: 5
      }
    })
    console.log(res.data.data, '文章评论')
    dispatch({
      type: 'article/saveComment',
      payload: res.data.data
    })
  }
}

// 获取文章的评论
export function likeAritcle (id: string, attitude: number): RootThunkAction {
  return async (dispatch) => {
    if (attitude === 1) {
      // 取消点赞
      await request.delete('/article/likings/' + id)
    } else {
      // 点赞
      await request.post('/article/likings', { target: id })
    }
    // 更新
    await dispatch(getArticleInfo(id))
  }
}

// 收藏
export function collectArticle (
  id: string,
  is_collected: boolean
): RootThunkAction {
  return async (dispatch) => {
    if (is_collected) {
      // 取消收藏
      await request.delete('/article/collections/' + id)
    } else {
      // 收藏
      await request.post('/article/collections', {
        target: id
      })
    }
    await dispatch(getArticleInfo(id))
  }
}

export function followUser (
  userId: number,
  is_follow: boolean
): RootThunkAction {
  return async (dispatch, getState) => {
    if (is_follow) {
      // 取消关注
      await request.delete('/user/followings/' + userId)
    } else {
      // 关注
      await request.post('/user/followings', {
        target: userId
      })
    }
    await dispatch(getArticleInfo(getState().articleDetail.info.art_id))
  }
}

export function addComment (
  articleId: string,
  content: string
): RootThunkAction {
  return async (dispatch) => {
    const res = await request.post<
      ApiResponse<{ new_obj: CommentDetail }>
    >('/comments', {
      target: articleId,
      content
    })
    dispatch({
      type: 'article/saveNewComment',
      payload: res.data.data.new_obj
    })
  }
}

// 获取评论的回复
export function getReplyList (id: string, offset: string): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<Comment>>('/comments', {
      params: {
        type: 'c',
        source: id,
        offset
      }
    })
    console.log(res.data.data, '评论列表')
  }
}
